package com.qiguliuxing.dts.admin.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.github.pagehelper.PageInfo;
import com.qiguliuxing.dts.admin.annotation.RequiresPermissionsDesc;
import com.qiguliuxing.dts.admin.service.AdminBillService;
import com.qiguliuxing.dts.admin.service.AdminDataAuthService;
import com.qiguliuxing.dts.admin.support.AuthSupport;
import com.qiguliuxing.dts.common.constant.ApiAdminConsts;
import com.qiguliuxing.dts.common.constant.LogParamsConsts;
import com.qiguliuxing.dts.common.util.ResponseUtils;
import com.qiguliuxing.dts.core.annotation.aoplog.WebLog;
import com.qiguliuxing.dts.core.support.JacksonUtil;
import com.qiguliuxing.dts.core.validator.Order;
import com.qiguliuxing.dts.core.validator.Sort;
import com.qiguliuxing.dts.db.bean.MerchantAccountTrace;
import com.qiguliuxing.dts.db.domain.DtsMerchantAccountTrace;
import com.qiguliuxing.dts.db.domain.DtsMerchantWithdrawalAccount;
import com.qiguliuxing.dts.service.merchant.WithdrawAccountService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Validated
@RestController
@RequestMapping("/admin/bill")
@Api(tags = ApiAdminConsts.Bill.PARENT)
public class AdminBillController {
    private static final Logger logger = LoggerFactory.getLogger(AdminBillController.class);

    @Autowired
    private AdminBillService billService;

    @Autowired
    private WithdrawAccountService withdrawAccountService;

    @PostMapping("/transfer")
    @RequiresPermissions("admin:bill:transfer")
    @RequiresPermissionsDesc(menu = { "系统管理", "账单管理" }, button = "付款到微信账号")
    @ApiOperation(value= ApiAdminConsts.Bill.TRANSFER)
    @WebLog(description = ApiAdminConsts.Bill.TRANSFER, persistence = true)
    public Object transfer(@ApiParam(value = "用户id") @RequestParam Integer userId,
                           @ApiParam(value = "金额（分）") @RequestParam Integer amount) {
        boolean payResult = billService.transfer(userId, amount);

        if (!payResult) {
            logger.info("系统管理->账单管理->付款到微信账号失败：{}", "处理错误！");
            return ResponseUtils.updatedDataFailed();
        }
        return ResponseUtils.ok();
    }

    @PostMapping("/payBank")
    @RequiresPermissions("admin:bill:payBank")
    @RequiresPermissionsDesc(menu = { "系统管理", "账单管理" }, button = "付款到银行卡")
    @ApiOperation(value= ApiAdminConsts.Bill.PAYBANK)
    @WebLog(description = ApiAdminConsts.Bill.PAYBANK, persistence = true)
    public Object payBank(@ApiParam(value = "银行编号") @RequestParam String bankCode,
                          @ApiParam(value = "银行卡") @RequestParam String bankNo,
                          @ApiParam(value = "账户名") @RequestParam String encTrueName,
                          @ApiParam(value = "金额（分）") @RequestParam Integer amount) {
        boolean payResult = billService.payBank(bankCode, bankNo, encTrueName, amount);

        if (!payResult) {
            logger.info("系统管理->账单管理->付款到银行卡失败：{}", "处理错误！");
            return ResponseUtils.updatedDataFailed();
        }
        return ResponseUtils.ok();
    }

    /**
     * 查询提现记录
     *
     * @param page
     * @param limit
     * @param sort
     * @param order
     * @return
     */
    @GetMapping("/list")
    @RequiresPermissions("merchant:bill:list")
    @RequiresPermissionsDesc(menu = { "商场管理", "提现记录" }, button = "查询")
    @ApiOperation(value=ApiAdminConsts.MerchantWithdraw.LIST)
    @WebLog(description = ApiAdminConsts.MerchantWithdraw.LIST, excludes = {LogParamsConsts.RESPONSE})
    public Object listWithdraw(@ApiParam(value = "页码",defaultValue = "1")  @RequestParam(defaultValue = "1") Integer page,
                               @ApiParam(value = "分页大小",defaultValue = "10")  @RequestParam(defaultValue = "10") Integer limit,
                               @ApiParam(value = "排序字段",defaultValue = "add_time")  @Sort @RequestParam(defaultValue = "add_time") String sort,
                               @ApiParam(value = "排序规则",defaultValue = "desc")  @Order @RequestParam(defaultValue = "desc") String order,
                               @ApiParam(value = "品牌商Id") Integer brandId,
                               @ApiParam(value = "提现账户")  String accountNo,
                               @ApiParam(value = "状态数组") @RequestParam(required = false) List<Byte> statusArray) {
        // 不做数据权限
        List<Integer> brandIds = null;
        List<MerchantAccountTrace> dtsMerchantAccountTraceList = withdrawAccountService.queryMerchantAccountTrace(brandIds, page, limit, sort, order,brandId,accountNo,statusArray);
        long total = PageInfo.of(dtsMerchantAccountTraceList).getTotal();
        Map<String, Object> data = new HashMap<>();
        data.put("total", total);
        data.put("items", dtsMerchantAccountTraceList);
        return ResponseUtils.ok(data);
    }

    @RequiresPermissions("admin:brokerage:approve")
    @RequiresPermissionsDesc(menu = { "商场管理", "提现记录" }, button = "审批销账")
    @PostMapping("/approve")
    @ApiOperation(value= ApiAdminConsts.Brokerage.APPROVE,notes = "body参数：{id:'',traceMsg:'',status:'状态'}")
    @WebLog(description = ApiAdminConsts.Brokerage.APPROVE,persistence = true)
    public Object approve(@RequestBody String body) {
        Integer traceId = JacksonUtil.parseInteger(body, "id");
        String traceMsg = JacksonUtil.parseString(body, "traceMsg");
        Byte status = JacksonUtil.parseByte(body, "status");
        boolean approveResult = billService.approve(traceId, traceMsg, status) > 0;
        if (!approveResult) {
            logger.info("商场管理->提现记录->审批销账失败：{}", "审批处理错误！");
            return ResponseUtils.updatedDataFailed();
        }
        return ResponseUtils.ok();
    }
}
